<template>
  <image
    v-if="imgSrc"
    class="x-image"
    :src="imgSrc"
    :mode="mode"
    :lazyLoad="lazyLoad"
    :style="{'background-color': background}"
    :show-menu-by-longpress="showLongPress"
    @click="onClick"
    @load="load"
    @error="error"
    @longpress="onLongPress"
  />
</template>

<script>
import $config from '@/config';
export default {
  name: 'XImage',
  components: {},
  props: {
    showLongPress: {
      type: Boolean,
      default: false
    },
    isBackground: {
      type: Boolean,
      default: false
    },
    lazyLoad: {
      type: Boolean,
      default: false
    },
    src: {
      type: [String, Object],
      default: ''
    },
    mode: {
      type: String,
      default: 'aspectFill'
    },
    size: {
      type: [String, Number],
      default: 400
    },
    // 根据不同appid加载不同的图片
    appid: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {};
  },
  computed: {
    background() {
      const color = ['#F7FAF7', '#FCECEC', '#F7F8FD', '#FDF2FC', '#FDFBF7'];
      return this.isBackground ? color[Math.floor(Math.random() * 5)] : 'transparent';
    },
    imgSrc() {
      // 以/assets 开头的路径地址，自动替换为远程cdn地址
      return this.src
        ? this.src.replace(/^\/assets/gi, this.appid ? `${$config.static}/${$config.isOpen ? $config.project : $config.appId}` : $config.static)
        : null;
    }
  },
  watch: {},
  created() {

  },
  methods: {
    onClick() {
      this.$emit('click');
    },
    load() {
      this.$emit('load');
    },
    error() {
      this.$emit('error');
    },
    onLongPress() {
      this.$emit('longPress');
    }
  }
};
</script>

<style lang="scss">
.x-image{ width: 100%; height: 100%; display: block; vertical-align: middle;}
</style>
